#!/usr/bin/env python3
"""
AI日志分析系统测试脚本
"""

import requests
import json
import time
import sys
from pathlib import Path

def test_backend_connection():
    """测试后端连接"""
    print("[SEARCH] 测试后端连接...")
    try:
        response = requests.get("http://localhost:8080/", timeout=5)
        if response.status_code == 200:
            print("[PASS] 后端服务连接正常")
            return True
        else:
            print(f"[FAIL] 后端服务响应异常: {response.status_code}")
            return False
    except requests.RequestException as e:
        print(f"[FAIL] 后端服务连接失败: {e}")
        return False

def test_ai_config():
    """测试AI配置"""
    print("[SEARCH] 测试AI配置...")
    try:
        response = requests.get("http://localhost:8080/ai/config", timeout=5)
        if response.status_code == 200:
            config = response.json()
            if config.get('api_key'):
                print("[PASS] AI配置正常")
                return True
            else:
                print("[WARN]  AI配置缺少API密钥")
                return False
        else:
            print(f"[FAIL] AI配置获取失败: {response.status_code}")
            return False
    except requests.RequestException as e:
        print(f"[FAIL] AI配置测试失败: {e}")
        return False

def test_ai_analysis():
    """测试AI分析功能"""
    print("[SEARCH] 测试AI分析功能...")
    
    # 检查是否有日志数据
    try:
        response = requests.get("http://localhost:8080/analysis", timeout=5)
        if response.status_code != 200:
            print("[WARN]  没有日志数据，跳过AI分析测试")
            return True
    except:
        print("[WARN]  无法获取分析数据，跳过AI分析测试")
        return True
    
    # 测试AI分析
    try:
        response = requests.post("http://localhost:8080/ai/analyze", timeout=30)
        if response.status_code == 200:
            result = response.json()
            if 'initial_analysis' in result:
                print("[PASS] AI分析功能正常")
                return True
            else:
                print("[WARN]  AI分析返回结果异常")
                return False
        else:
            print(f"[FAIL] AI分析请求失败: {response.status_code}")
            return False
    except requests.RequestException as e:
        print(f"[FAIL] AI分析测试失败: {e}")
        return False

def test_ai_question():
    """测试AI问答功能"""
    print("[SEARCH] 测试AI问答功能...")
    
    test_question = "请简单介绍一下这个日志分析系统"
    
    try:
        response = requests.post("http://localhost:8080/ai/ask", 
                               json={"question": test_question}, 
                               timeout=30)
        if response.status_code == 200:
            result = response.json()
            if 'answer' in result:
                print("[PASS] AI问答功能正常")
                return True
            else:
                print("[WARN]  AI问答返回结果异常")
                return False
        else:
            print(f"[FAIL] AI问答请求失败: {response.status_code}")
            return False
    except requests.RequestException as e:
        print(f"[FAIL] AI问答测试失败: {e}")
        return False

def test_frontend_connection():
    """测试前端连接"""
    print("[SEARCH] 测试前端连接...")
    try:
        response = requests.get("http://localhost:5173/", timeout=5)
        if response.status_code == 200:
            print("[PASS] 前端服务连接正常")
            return True
        else:
            print(f"[FAIL] 前端服务响应异常: {response.status_code}")
            return False
    except requests.RequestException as e:
        print(f"[FAIL] 前端服务连接失败: {e}")
        return False

def main():
    """主测试函数"""
    print("[TEST] AI日志分析系统测试")
    print("=" * 50)
    
    # 测试后端连接
    if not test_backend_connection():
        print("\n[FAIL] 后端服务未启动，请先启动系统")
        sys.exit(1)
    
    # 测试AI配置
    ai_config_ok = test_ai_config()
    
    # 测试AI功能
    if ai_config_ok:
        test_ai_analysis()
        test_ai_question()
    else:
        print("\n[WARN]  AI功能未配置，跳过AI测试")
        print("   请配置 config/ai_config.json 中的API密钥")
    
    # 测试前端连接
    test_frontend_connection()
    
    print("\n" + "=" * 50)
    print("[SUCCESS] 测试完成!")
    print("\n系统状态:")
    print("  后端服务: [PASS] 运行中")
    if ai_config_ok:
        print("  AI功能: [PASS] 已配置")
    else:
        print("  AI功能: [WARN]  未配置")
    print("  前端服务: [PASS] 运行中")
    print("\n访问地址:")
    print("  前端界面: http://localhost:5173")
    print("  后端API: http://localhost:8080")

if __name__ == "__main__":
    main() 